package com.sh.caryr.erp.controller.stock;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.sh.caryr.erp.entity.ResultMessage;
import com.sh.caryr.erp.entity.enums.SkuRecordHandleType;
import com.sh.caryr.erp.entity.stock.Sku;
import com.sh.caryr.erp.exception.ResultCode;
import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.exception.RestServiceException;
import com.sh.caryr.erp.service.ISkuRecordService;
import com.sh.caryr.erp.service.ISkuService;
import com.sh.caryr.erp.util.ERPConstants;
import com.sh.caryr.erp.util.MyBatisUtil;
import com.sh.caryr.erp.util.UtilityTool;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/sku")
@SessionAttributes("user")
public class SkuController {

    private final ISkuService skuService;

    private final ISkuRecordService skuRecordService;

    @Autowired
    public SkuController(ISkuRecordService skuRecordService, ISkuService skuService) {
        this.skuRecordService = skuRecordService;
        this.skuService = skuService;
    }

    @ApiOperation(value = "Get Count", notes = "Get Count")
    @RequestMapping(value = "/count", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @SuppressWarnings("unchecked")
    public ResultMessage<Integer> countProducts(@ModelAttribute("user") User operator) {
        Wrapper wrapper = MyBatisUtil.getIsActiveWrapper();
        MyBatisUtil.addAuthFilter(MyBatisUtil.getIsActiveWrapper(), operator, ERPConstants.AUTH_TARGET_SKU, false, true);
        return new ResultMessage<>(skuService.selectCount(wrapper));
    }

    @ApiOperation(value = "Get entity list", notes = "Get entity list")
    @RequestMapping(method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @SuppressWarnings("unchecked")
    public ResultMessage<List<Sku>> findSkus(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(name = "search[value]", required = false) String filters,
            @RequestParam(defaultValue = "id") String orderBy,
            @RequestParam(defaultValue = "false") Boolean isAsc,
            @ModelAttribute("user") User operator) {
        return MyBatisUtil.searchEntities(current, size, filters, orderBy, isAsc, operator, skuService);
    }

    @ApiOperation(value = "获取单个sku信息", notes = "获取单个sku信息")
    @ApiImplicitParam(name = "id", value = "skuId", required = true, dataType = "long")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<Sku> findSkuById(@PathVariable long id) {
        return new ResultMessage<>(skuService.selectById(id));
    }

    @ApiOperation(value = "创建sku", notes = "根据sku对象创建sku")
    @ApiImplicitParam(name = "sku", value = "sku详细实体", required = true, dataType = "Sku")
    @Transactional
    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<Sku> insertSku(@RequestBody Sku sku,
                                        @ModelAttribute("user") User operator) {
        if (skuService.insert(sku)) {
            skuRecordService.insert(sku, operator, SkuRecordHandleType.CREATE);
            return new ResultMessage<>(sku);
        } else {
            throw new RestServiceException(ResultCode.CREATE_FAILED);
        }
    }

    @ApiOperation(value = "Update", notes = "Update")
    @ApiImplicitParam(name = "sku", value = "sku", required = true, dataType = "Sku")
    @Transactional
    @RequestMapping(method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage<Sku> updateSkuById(@RequestBody Sku sku, @ModelAttribute("user") User operator) {
        sku.setUpdateAt(new Date());
        sku.setUpdateBy(operator.getId());
        if (skuService.updateById(sku)) {
            Sku skuOld = skuService.selectById(sku.getId());
            skuOld.setRemark(sku.getRemark());
            skuRecordService.insert(skuOld, operator, SkuRecordHandleType.UPDATE);
            return new ResultMessage<>(sku);
        } else {
            throw new RestServiceException(ResultCode.UPDATE_FAILED);
        }
    }

    @ApiOperation(value = "批量删除sku", notes = "根据url的id来指定删除sku")
    @ApiImplicitParam(name = "ids", value = "skuIds", required = true, dataType = "String")
    @Transactional
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.OK)
    public ResultMessage deleteSkus(@PathVariable String ids,
                                    @ModelAttribute("user") User operator) {
        List<Long> list = UtilityTool.convertStringArray2LongList(ids.split(","));
        try {
            UtilityTool.softDelete(Sku.class, list, skuService);
            //记录skuRecord
            for (Long id : list) {
                Sku sku = skuService.selectById(id);
                skuRecordService.insert(sku, operator, SkuRecordHandleType.DELETE);
            }
            return new ResultMessage();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RestServiceException(ResultCode.DELETE_NOT_FOUND);
        }
    }
}
